<template>
  <div class="group-detail-page" >
    <el-card shadow="hover">
      <template #header>
        <h2>拼团进度</h2>
        <div class="countdown">剩余 {{ restMinutes }}:{{ restSeconds }}</div>
      </template>

      <el-progress
        :percentage="percent"
        :format="() => `${detail.joinedCount}/${detail.requiredCount}`"
      />

      <el-avatar-group class="member-avatars">
        <el-avatar
          v-for="m in detail.members"
          :key="m.userId"
        />
      </el-avatar-group>

      <el-row justify="center" class="actions">
        <el-button type="primary" @click="copyInvite">复制邀请码</el-button>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getGroupDetailById } from '@/api/groupbuy'
import useClipboard from '@/composables/useClipboard'

/* ---------- 基础状态 ---------- */
const route   = useRoute()
const groupId = Number(route.params.groupId)

const detail = ref({
  group: {},
  members: [],
  joinedCount: 0,
  requiredCount: 1
})

/* ---------- 拉取详情 ---------- */
async function fetchDetail () {
  const res = await getGroupDetailById(groupId)
  console.log(res)
  if (res.data.code === '0' || res.data.code === '200') {
    detail.value = res.data.data
  } else {
    ElMessage.error(res.message || '获取拼团信息失败')
  }
}
onMounted(fetchDetail)

/* ---------- 倒计时 ---------- */
const restSecondsAll = ref(0)
let timer = null

function startCountdown () {
  const end = new Date(detail.value.group.expireTime).getTime()
  timer = setInterval(() => {
    const diff = Math.max(0, Math.floor((end - Date.now()) / 1000))
    restSecondsAll.value = diff
    if (diff === 0) clearInterval(timer)
  }, 1000)
}

watch(() => detail.value.group.expireTime, startCountdown)
onBeforeUnmount(() => timer && clearInterval(timer))

const restMinutes = computed(() =>
  String(Math.floor(restSecondsAll.value / 60)).padStart(2, '0'))
const restSeconds = computed(() =>
  String(restSecondsAll.value % 60).padStart(2, '0'))

/* ---------- 进度百分比 ---------- */
const percent = computed(() => {
  const { joinedCount = 0, requiredCount = 1 } = detail.value
  return Math.min(100, Math.round((joinedCount / requiredCount) * 100))
})

/* ---------- 复制邀请码 ---------- */
const { copy } = useClipboard()
function copyInvite () {
  copy(detail.value.group.inviteCode)
}
</script>



<style scoped>
.group-detail-page {
  padding-bottom: 1px;
  max-width: 600px;
  margin: 40px auto;
}
.countdown {
  font-size: 14px;
  color: #f56c6c;
}
.member-avatars {
  margin: 20px 0;
}
.actions {
  margin-top: 10px;
  gap: 12px;
}
</style>
